<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF翻译工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        body {
            padding-top: 4rem;
            background-color: #f8f9fa;
            position: relative;
            min-height: 100vh;
            margin: 0;
        }
        
        .background-slideshow {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            overflow: hidden;
        }
        
        .background-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 1s ease-in-out;
            object-fit: cover;
        }
        
        .background-image.active {
            opacity: 1;
        }
        
        .container {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            position: relative;
            z-index: 1;
        }
        
        .progress {
            height: 25px;
            background-color: #f8f9fa;
        }
        
        .progress-bar {
            transition: width 0.3s ease-in-out;
        }
        
        .file-item {
            background-color: rgba(255, 255, 255, 0.9);
        }
        
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            margin: 20px 0;
            cursor: pointer;
        }
        
        .upload-area:hover {
            border-color: #0d6efd;
        }
        
        .file-list {
            margin-top: 20px;
        }
        
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border: 1px solid #ddd;
            margin-bottom: 5px;
            border-radius: 5px;
        }
        
        .file-item:hover {
            background-color: #f8f9fa;
        }
        
        .navbar {
            background-color: rgba(255, 255, 255, 0.95);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .model-info {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        .model-info h5 {
            color: #0d6efd;
            margin-bottom: 15px;
        }

        .model-feature {
            display: flex;
            align-items: start;
            margin-bottom: 10px;
            padding: 10px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 5px;
        }

        .model-feature i {
            margin-right: 10px;
            color: #0d6efd;
        }

        .deepseek-info {
            margin-top: 15px;
            padding: 15px;
            background: rgba(13, 110, 253, 0.1);
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light fixed-top">
        <div class="container">
            <a class="navbar-brand" href="/">PDF翻译工具</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link active" href="/">主页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/about">关于</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 背景轮播容器 -->
    <div class="background-slideshow" id="backgroundSlideshow"></div>
    
    <div class="container">
        <h1 class="text-center mb-4">PDF翻译工具</h1>
        
        <!-- 模型介绍部分 -->
        <div class="model-info mb-4">
            <h5>翻译模型说明</h5>
            <div class="model-feature">
                <i class="bi bi-google"></i>
                <div>
                    <strong>Google翻译（免费）</strong>
                    <p class="mb-0">快速、稳定的机器翻译服务，支持多种语言之间的互译，适合一般文档翻译需求。</p>
                </div>
            </div>
            <div class="deepseek-info">
                <h6 class="mb-3">DeepSeek 翻译服务</h6>
                <div class="alert alert-warning" role="alert">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    <strong>服务说明：</strong> 由于近期受到大量攻击，api请求速度可能较慢，同时由于需要保持格式和图表，会带来大量token消耗，请耐心等待。
                </div>
                <div class="model-feature">
                    <i class="bi bi-chat"></i>
                    <div>
                        <strong>DeepSeek Chat (v3)</strong>
                        <p class="mb-0">最新的v3模型，提供更准确的翻译和更好的上下文理解能力，特别适合专业文献翻译。</p>
                    </div>
                </div>
                <div class="model-feature">
                    <i class="bi bi-braces"></i>
                    <div>
                        <strong>DeepSeek Reasoner (r1)</strong>
                        <p class="mb-0">专门针对科技文献优化的模型，在数学公式、专业术语等方面表现出色。</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- API设置 -->
        <div class="mb-4">
            <h5>API设置</h5>
            <div class="input-group">
                <input type="text" id="apiKey" class="form-control" placeholder="请输入DeepSeek API密钥">
                <button class="btn btn-primary" onclick="saveApiKey()">保存</button>
            </div>
            <div class="mt-2 text-muted">
                <small>
                    <i class="bi bi-info-circle"></i>
                    需要DeepSeek API？请访问 <a href="https://platform.deepseek.com/" target="_blank">DeepSeek平台</a> 申请API密钥。
                </small>
            </div>
            <div class="form-check mt-2">
                <input class="form-check-input" type="radio" name="model" id="googleTranslate" value="" checked>
                <label class="form-check-label" for="googleTranslate">
                    Google翻译（免费）
                </label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="radio" name="model" id="deepseekChat" value="deepseek-chat">
                <label class="form-check-label" for="deepseekChat">
                    DeepSeek Chat (v3)
                </label>
            </div>
            <div class="form-check">
                <input class="form-check-input" type="radio" name="model" id="deepseekReasoner" value="deepseek-reasoner">
                <label class="form-check-label" for="deepseekReasoner">
                    DeepSeek Reasoner (r1)
                </label>
            </div>
        </div>

        <!-- 文件上传区域 -->
        <div class="upload-area" onclick="document.getElementById('fileInput').click()">
            <input type="file" id="fileInput" accept=".pdf" style="display: none" onchange="uploadFile()">
            <i class="fas fa-cloud-upload-alt"></i>
            <h5>点击或拖拽PDF文件到此处</h5>
            <p class="text-muted">支持的文件格式: PDF</p>
        </div>

        <!-- 翻译进度 -->
        <div id="progressArea" style="display: none;">
            <h5>翻译进度</h5>
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
            </div>
            <p id="progressText" class="text-center mt-2"></p>
        </div>

        <!-- 文件列表 -->
        <div class="row mt-4">
            <!-- 上传文件列表 -->
            <div class="col-md-6">
                <h5>源文件</h5>
                <div id="uploadedFiles" class="file-list"></div>
            </div>
            <!-- 翻译后文件列表 -->
            <div class="col-md-6">
                <h5>翻译后文件</h5>
                <div id="translatedFiles" class="file-list"></div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 保存API密钥
        function saveApiKey() {
            const apiKey = document.getElementById('apiKey').value;
            if (apiKey) {
                localStorage.setItem('deepseekApiKey', apiKey);
                alert('API密钥已保存');
            }
        }

        // 上传文件
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) return;
            if (!file.name.toLowerCase().endsWith('.pdf')) {
                alert('请上传PDF文件');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            // 添加选中的翻译模型
            const selectedModel = document.querySelector('input[name="model"]:checked').value;
            if (selectedModel) {
                formData.append('model', selectedModel);
            }

            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    showProgress(data.translation_id);
                    updateFileList();
                } else {
                    alert(data.error || '上传失败');
                }
            } catch (error) {
                alert('上传失败: ' + error.message);
            }
        }

        // 显示进度
        function showProgress(translationId) {
            const progressArea = document.getElementById('progressArea');
            const progressBar = document.querySelector('.progress-bar');
            const progressText = document.getElementById('progressText');
            
            progressArea.style.display = 'block';
            
            const checkProgress = async () => {
                try {
                    const response = await fetch(`/progress/${translationId}`);
                    const data = await response.json();
                    
                    if (response.ok) {
                        progressBar.style.width = `${data.progress}%`;
                        progressBar.setAttribute('aria-valuenow', data.progress);
                        
                        if (data.status === 'completed') {
                            progressText.textContent = '翻译完成';
                            updateFileList();
                            return;
                        } else if (data.status === 'error') {
                            progressText.textContent = `翻译失败: ${data.message}`;
                            return;
                        }
                        
                        progressText.textContent = `正在翻译... ${data.progress}%`;
                        setTimeout(checkProgress, 1000);
                    }
                } catch (error) {
                    progressText.textContent = '获取进度失败';
                }
            };
            
            checkProgress();
        }

        // 更新文件列表
        async function updateFileList() {
            try {
                const response = await fetch('/files');
                const data = await response.json();
                
                const uploadedFiles = document.getElementById('uploadedFiles');
                const translatedFiles = document.getElementById('translatedFiles');
                
                uploadedFiles.innerHTML = '';
                translatedFiles.innerHTML = '';
                
                // 显示源文件
                data.uploads.forEach(file => {
                    uploadedFiles.innerHTML += `
                        <div class="file-item">
                            <span>${file.name}</span>
                            <div>
                                <button onclick="previewPdf('${file.name}')" class="btn btn-sm btn-info me-2">预览</button>
                                <a href="/download/${encodeURIComponent(file.name)}" class="btn btn-sm btn-primary">下载</a>
                            </div>
                        </div>
                    `;
                });
                
                // 显示翻译后文件
                data.translated.forEach(file => {
                    translatedFiles.innerHTML += `
                        <div class="file-item">
                            <span>${file.name}</span>
                            <div>
                                <button onclick="previewPdf('${file.name}')" class="btn btn-sm btn-info me-2">预览</button>
                                <a href="/download/${encodeURIComponent(file.name)}" class="btn btn-sm btn-primary">下载</a>
                            </div>
                        </div>
                    `;
                });

                // 如果没有文件，显示提示信息
                if (data.uploads.length === 0) {
                    uploadedFiles.innerHTML = '<div class="text-muted">暂无源文件</div>';
                }
                if (data.translated.length === 0) {
                    translatedFiles.innerHTML = '<div class="text-muted">暂无翻译文件</div>';
                }
            } catch (error) {
                console.error('更新文件列表失败:', error);
            }
        }

        // 预览PDF
        function previewPdf(filename) {
            const width = 1000;
            const height = 800;
            const left = (screen.width - width) / 2;
            const top = (screen.height - height) / 2;
            window.open(`/preview/${encodeURIComponent(filename)}`, '_blank',
                `width=${width},height=${height},left=${left},top=${top}`);
        }

        // 背景轮播功能
        let currentBackgroundIndex = 0;
        let backgrounds = [];
        
        async function loadBackgrounds() {
            try {
                const response = await fetch('/get_backgrounds');
                backgrounds = await response.json();
                if (backgrounds.length > 0) {
                    initializeSlideshow();
                }
            } catch (error) {
                console.error('加载背景图片失败:', error);
            }
        }
        
        function initializeSlideshow() {
            const container = document.getElementById('backgroundSlideshow');
            container.innerHTML = '';
            
            backgrounds.forEach((bg, index) => {
                const img = document.createElement('img');
                img.src = `/res/${bg}`;
                img.classList.add('background-image');
                if (index === 0) img.classList.add('active');
                container.appendChild(img);
            });
            
            setInterval(changeBackground, 5000); // 每5秒切换一次
        }
        
        function changeBackground() {
            const images = document.querySelectorAll('.background-image');
            if (images.length === 0) return;
            
            images[currentBackgroundIndex].classList.remove('active');
            currentBackgroundIndex = (currentBackgroundIndex + 1) % images.length;
            images[currentBackgroundIndex].classList.add('active');
        }

        // 页面加载时初始化背景轮播
        document.addEventListener('DOMContentLoaded', () => {
            loadBackgrounds();
            updateFileList();
            
            // 从localStorage加载API密钥
            const savedApiKey = localStorage.getItem('deepseekApiKey');
            if (savedApiKey) {
                document.getElementById('apiKey').value = savedApiKey;
            }
        });

        // 拖拽上传
        const uploadArea = document.querySelector('.upload-area');
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#0d6efd';
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.style.borderColor = '#ddd';
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#ddd';
            
            const file = e.dataTransfer.files[0];
            if (file) {
                document.getElementById('fileInput').files = e.dataTransfer.files;
                uploadFile();
            }
        });
    </script>
</body>
</html>
